package com.demo.utils;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Enumeration;

public class CertUtils {

    public static PrivateKey getPrivateKey(String path,String password,String type){
        PrivateKey privateKey=null;
        try{
            KeyStore keyStore=KeyStore.getInstance(type);
            FileInputStream fileInputStream=new FileInputStream(path);
            char[] passChar=password.toCharArray();
            keyStore.load(fileInputStream,passChar);
            Enumeration<String> enumeration=keyStore.aliases();
            String keyAlias=null;
            while (enumeration.hasMoreElements()){
                keyAlias=enumeration.nextElement();
                privateKey=(PrivateKey)keyStore.getKey(keyAlias,passChar);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return privateKey;
    }

    public static PublicKey getPublicKey(String path) {
        PublicKey publicKey = null;
        FileInputStream fileInputStream = null;
        CertificateFactory certificateFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            fileInputStream = new FileInputStream(path);
            Certificate certificate=certificateFactory.generateCertificate(fileInputStream);
            publicKey=certificate.getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }


}
